# _*_ coding : utf-8 _*_
# @Time : 2023/12/11 10:54
# @Author : 韩宗森
# @File : 19_站长素材
# @Project : pythonProject

from lxml import etree
import urllib.request


# (1)请求对象的定制
# (2)获取网页的源码
# (3)下载

# 需求 下载图片
# 第一页 https://sc.chinaz.com/tupian/meinvtupian.html
# 第二页 https://sc.chinaz.com/tupian/meinvtupian_2.html
# 第3页 https://sc.chinaz.com/tupian/meinvtupian_3.html

# (1)请求对象的定制
def create_request(page):
    if (page == 1):
        url = 'https://sc.chinaz.com/tupian/meinvtupian.html'
    else:
        url = 'https://sc.chinaz.com/tupian/meinvtupian_' + str(page) + '.html'

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'
    }
    # 请求对象的定制
    request = urllib.request.Request(url=url, headers=headers)

    return request


# (2)获取网页的源码
def get_content(request):
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    return content


# (3)下载
def down_load(content):
    # 解析服务器响应的文件
    tree = etree.HTML(content)
    # 获取想要的数据 https://scpic.chinaz.net/files/default/imgs/2023-10-21/52a8d4fea21db183_s.jpg
    # 图片地址  一般涉及图片的网站都会进行懒加载
    src_list = tree.xpath('//div[@class="tupian-list com-img-txt-list"]/div/img/@data-original')
    # 图片名称
    name_list = tree.xpath('//div[@class="tupian-list com-img-txt-list"]/div/img/@alt')
    for i in range(len(name_list)):
        name = name_list[i]
        src = src_list[i]
        url = 'https:' + src
        # urllib.request.urlretrieve('图片地址','文件的名字')
        # 下载图片  放到文件夹下
        urllib.request.urlretrieve(url=url,filename='./站长图片/'+name+'.jpg')




if __name__ == '__main__':
    start_page = 1;  # 开始页码
    end_page = 10;  # 结束页码

    for page in range(start_page, end_page + 1):
        # (1)请求对象的定制
        request = create_request(page)
        # (2)获取网页的源码
        content = get_content(request)
        # print(content)
        # (3)下载
        down_load(content)
